<!--
 * @Descripttion: 附件列表  ------没有搞完
 * @version: 
 * @Author: hutao
 * @Date: 2021-12-30 16:07:59
 * @LastEditors: hutao
 * @LastEditTime: 2023-05-12 14:56:18
-->
<template>
  <div v-if="!hideFiles">
    <el-upload
      class="ht-upload"
      v-if="!readonly"
      :style="drag ? 'width:100%;height:108px;max-width:368px' : ''"
      :show-file-list="false"
      :disabled="disabled"
      :on-success="onSuccess"
      :before-upload="beforeUpload"
      :drag="drag"
      action="/file-management-service/api/filing/file/upload"
      multiple
    >
      <slot>
        <!-- <i class="el-icon-upload"></i> -->
        <div
          style="margin-top:8px;font-size:12px;color:#999"
          class="el-upload__text"
        >
          拖动文件到此处，或<br /><em>点击上传</em>
        </div></slot
      >

      <!-- <div class="el-upload__tip"
                     slot="tip">只能上传jpg/png文件，且不超过5M</div> -->
    </el-upload>
    <ul class="ht-ul-upload" v-if="!hideFiles">
      <li :key="item.fileToken" v-for="(item, index) in state.filesInfo">
        <a @click="downLoadFile(item)"
          ><i class="le-icon el-icon-document" style="margin-right:7px"></i
          >{{ item.fileName }}</a
        >
        <span v-if="!disabled && !readonly" style="margin-right:16px">
          <i class="el-icon  el-icon-circle-check"></i>
          <i
            class="el-icon  el-icon-close"
            @click="delItem(item, index)"
            title="删除"
          ></i>
        </span>
      </li>
    </ul>

    <a :href="state.fileSrc" target="_blank" v-show="false" ref="download1"></a>
  </div>
  <span v-else style="cursor:pointer;color:var(--primary)">
    <i slot="reference" class="el-icon-paperclip" @click="showDetails">{{
      state.filesInfo.length
    }}</i>

    <el-dialog
      title="附件详情"
      append-to-body
      :visible.sync="state.visible"
      width="400px"
    >
      <ul class="ht-ul-upload" v-if="hideFiles">
        <li
          :key="item.fileToken"
          @click="downLoadFile(item)"
          style="height:30px;line-height:30px;color:var(--primary);cursor:pointer"
          v-for="item in state.filesInfo"
        >
          <a
            ><i class="le-icon el-icon-document" style="margin-right:7px"></i
            >{{ item.fileName }}</a
          >
        </li>
      </ul>

      <a
        :href="state.fileSrc"
        target="_blank"
        v-show="false"
        ref="download1"
      ></a>
    </el-dialog>
  </span>
</template>
<script lang="ts">
import { _axios } from 'vue-kst-auth';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
interface State {
  /** 数据状态 */
  loading: boolean;
  visible: boolean;
  fileSrc: string;
  /** 图片地址 */
  fileToken: string[];
  dialogVisible: boolean;
  /**   附件详情列表 */
  filesInfo: FileType[];
}
interface FileType {
  fileName: string;
  fileSize?: number;
  fileToken?: string;
  fileType?: string;
}
@Component
export default class Index extends Vue {
  @Prop() value!: string;
  /** 是否是数据结构 */
  @Prop() isArray!: boolean;
  /** 隐藏附件的内容 */
  @Prop() hideFiles!: boolean;
  @Prop({ default: true }) drag!: boolean;
  /* 是否只读 */
  @Prop({ default: false }) readonly?: boolean;
  /** 是否禁用 */
  @Prop() disabled?: boolean;
  /** 数据 */
  state: State = {
    loading: false,
    visible: false,
    fileSrc: '',
    fileToken: [],
    filesInfo: [],
    dialogVisible: false,
  };
  /** 生命周期 */
  created() {
    //this.onValue(this.value);
  }
  showDetails() {
    if (this.state.filesInfo.length) {
      this.state.visible = true;
    }
  }
  /** 方法 */
  /** 上传文件前验证 */

  /** 附件上传之前的判断 */
  beforeUpload(file: File) {
    const isLt10MB = file.size / 1024 / 1024 < 5;
    const arr = ['jpg', 'png', 'xlsx', 'lsx', 'doc', 'docx', 'pdf'];
    const lastArr = file.name.split('.');
    const type = lastArr[lastArr.length - 1];
    if (!isLt10MB) {
      this.$message.error('大小不能超过 5MB!');
    }
    if (arr.includes(type)) {
      return true;
    } else {
      this.$notify.error(`只能上传${arr.toString()}格式文件`);
      return false;
    }
  }
  /**下载文件 */
  downLoadFile(item: any) {
    this.state.fileSrc = `/file-management-service/api/filing/file/download/${item.fileToken}`;
    setTimeout(() => {
      const adom: any = this.$refs.download1;
      adom.click();
    }, 100);
  }
  /** 附件上传成功 */
  onSuccess(response: { fileToken: string }) {
    //this.state.files.push(response.fileToken);
    this.getFileInfo(response.fileToken);
  }
  /** 获取到的附件列表详情 */
  getFileInfo(id: string) {
    _axios.get('/file-management-service/api/filing/file/' + id).then((res) => {
      this.state.filesInfo.push(res.data);
    });
  }
  /** 删除附件列表 */
  delItem(item: FileType, index: number) {
    const { filesInfo } = this.state;
    if (item.fileToken) {
      filesInfo.splice(index, 1);
      this.state.filesInfo = filesInfo;
    }
  }
  /** 请求所有的附件信息 */
  async getAllFileInfo() {
    const { fileToken } = this.state;
    //this.state.filesInfo = [];
    for (let i = 0; i < fileToken.length; i++) {
      if (
        this.state.filesInfo.findIndex(
          (item) => item.fileToken === fileToken[i]
        ) < 0
      ) {
        await _axios
          .get('/file-management-service/api/filing/file/' + fileToken[i])
          .then((res) => {
            this.state.filesInfo.push(res.data);
          });
      }
    }
  }
  /** 监听 */
  /** 计算属性 */
  get fileList() {
    return [];
  }
  @Watch('state.filesInfo')
  onFileToken(val: FileType[], old: string) {
    if (!this.readonly) {
      if (this.isArray) {
        this.$emit('change', val);
      } else {
        const arr: string[] = [];
        val.forEach((item) => {
          if (item.fileToken) arr.push(item.fileToken);
        });
        this.$emit('input', arr.toString());
        this.$emit('change', arr);
      }
    }
  }
  @Watch('value', { immediate: true })
  onValue(val: any, oldValue: any) {
    if (JSON.stringify(val) !== JSON.stringify(oldValue)) {
      if (val) {
        if (Array.isArray(val)) {
          if (this.isArray) {
            this.state.filesInfo = val;
          } else {
            this.state.fileToken = val;
            this.getAllFileInfo();
          }
        } else {
          this.state.fileToken = val.split(',');
          this.getAllFileInfo();
        }
      } else {
        this.state.fileToken = [];
      }
    }
  }
}
</script>
<style lang="scss" scoped>
ul,
li {
  margin: 0;
  padding: 0;
}
.ht-ul-upload {
  li {
    width: 100%;
    list-style: none;
    padding: 0 8px;
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    a {
      color: #606266;
      font-size: 12px;
    }
    .el-icon-close {
      display: none;
    }
    &:hover {
      background: #eee;
      a {
        color: var(--primary);
      }
      .el-icon-close {
        display: block;
        line-height: 40px;
      }
      .el-icon-circle-check {
        display: none;
      }
    }
    .el-icon-circle-check {
      color: var(--primary);
    }
  }
}
</style>
